// src/components/racing/TrackDetail.jsx
import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { getItem } from '../../utils/localStorage';
import { useAuth } from '../../contexts/AuthContext';
import { useApp } from '../../contexts/AppContext';

const TrackDetail = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const { user } = useAuth();
  const { setSelectedTrack } = useApp();
  const [track, setTrack] = useState(null);

  useEffect(() => {
    const storedTracks = JSON.parse(getItem('tracks') || '[]');
    const foundTrack = storedTracks.find((t) => t.id === parseInt(id));
    if (foundTrack) {
      setTrack(foundTrack);
      setSelectedTrack(foundTrack);
    }
  }, [id, setSelectedTrack]);

  if (!track) {
    return <div className="text-center py-8">加载中...</div>;
  }

  const handleBooking = () => {
    if (!user) {
      navigate('/login');
      return;
    }
    navigate('/vehicles');
  };

  return (
    <div className="space-y-6">
      <div className="aspect-w-16 aspect-h-9">
        <img
          src={track.image}
          alt={track.name}
          className="w-full h-64 object-cover rounded-lg shadow-md"
        />
      </div>
      <div className="bg-white rounded-lg shadow-md p-6">
        <h1 className="text-3xl font-bold text-gray-900">{track.name}</h1>
        <p className="mt-4 text-gray-600">{track.description}</p>
        <div className="mt-6 space-y-4">
          <div className="flex items-center">
            <span className="text-gray-600">位置：</span>
            <span className="ml-2">{track.location}</span>
          </div>
        </div>
        <button
          onClick={handleBooking}
          className="mt-8 w-full bg-blue-600 text-white py-3 px-6 rounded-md hover:bg-blue-700 transition-colors"
        >
          选择赛车
        </button>
      </div>
    </div>
  );
};

export default TrackDetail;